﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI.WebControls;
using System.Net;
using WinnerCMS.Common;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 上传辅助类
    /// </summary>
    public static class UpFileHepler
    {
        /// <summary>
        /// 检查后缀名是否合法
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="isAdmin"></param>
        /// <returns></returns>
        public static bool Check(string fileName, bool isAdmin)
        {
            byte modelId;
            if (byte.TryParse(HttpContext.Current.Request["ModelId"], out modelId) == false)
            {
                return Check(fileName);
            }
            string fileTypes;
            if (isAdmin)
                fileTypes = ModelManage.GetInfo(modelId).AdminFileTypes;
            else
                fileTypes = ModelManage.GetInfo(modelId).MemberFileTypes;

            string extension = new FileInfo(fileName).Extension;
            return fileTypes.Split(',').Any(E => E.Equals(extension, StringComparison.CurrentCultureIgnoreCase));
        }

        /// <summary>
        /// 检查后缀名是否合法
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool Check(string fileName)
        {
            CMSConfig config = CMSConfig.Instance();

            string extension = new FileInfo(fileName).Extension;
            return config.FileTypes.Any(E => E.Equals(extension, StringComparison.CurrentCultureIgnoreCase));
        }

        /// <summary>
        /// 上传文件 方法
        /// </summary>
        /// <param name="fileNamePath"></param>
        /// <param name="toFilePath"></param>
        /// <returns>返回上传处理结果   格式说明： 0|file.jpg|msg   成功状态|文件名|消息    </returns>
        public static string UpLoadFile(string fileNamePath, string toFilePath)
        {
            try
            {
                //获取要保存的文件信息
                FileInfo file = new FileInfo(fileNamePath);
                //获得文件扩展名
                string fileNameExt = file.Extension;

                //验证合法的文件
                if (Check(fileNameExt))
                {
                    //生成将要保存的随机文件名
                    string fileName = MakeFileName() + fileNameExt;
                    //检查保存的路径 是否有/结尾
                    if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";

                    //按日期归类保存
                    string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
                    if (true)
                    {
                        toFilePath += datePath;
                    }

                    //获得要保存的文件路径
                    string serverFileName = toFilePath + fileName;
                    //物理完整路径                    
                    string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);

                    //检查是否有该路径  没有就创建
                    if (!Directory.Exists(toFileFullPath))
                    {
                        Directory.CreateDirectory(toFileFullPath);
                    }

                    //将要保存的完整文件名                
                    string toFile = toFileFullPath + fileName;

                    //创建WebClient实例       
                    WebClient myWebClient = new WebClient();
                    //设定windows网络安全认证   方法1
                    myWebClient.Credentials = CredentialCache.DefaultCredentials;


                    //要上传的文件       
                    FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                    //FileStream fs = OpenFile();       
                    BinaryReader r = new BinaryReader(fs);
                    //使用UploadFile方法可以用下面的格式       

                    byte[] postArray = r.ReadBytes((int) fs.Length);
                    Stream postStream = myWebClient.OpenWrite(toFile, "PUT");
                    if (postStream.CanWrite)
                    {
                        postStream.Write(postArray, 0, postArray.Length);
                    }
                    else
                    {
                        return "0|" + serverFileName + "|" + "文件目前不可写";
                    }
                    postStream.Close();


                    return "1|" + serverFileName + "|" + "文件上传成功";
                }
                return "0|errorfile|" + "文件格式非法";
            }
            catch (Exception e)
            {
                return "0|errorfile|" + "文件上传失败,错误原因：" + e.Message;
            }
        }

        private static string MakeFileName()
        {
            Random rand = new Random(unchecked((int) DateTime.Now.Ticks));
            int I = rand.Next(0, 100);
            return DateTime.Now.ToString("yyyyMMddhhmmssfff") + I;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileUpload"></param>
        /// <returns>文件相对路径</returns>
        public static string UpLoadFile(FileUpload fileUpload)
        {
            string UploadDir = "~/UpLoadFolder/"; //图片保存的文件夹
            //图片保存的文件夹路径
            string path = HttpServer.MapPath(UploadDir);
            //每天上传的图片一个文件夹
            string folder = DateTime.Now.ToString("yyyyMM");
            //如果文件夹不存在，则创建
            if (!Directory.Exists(path + folder))
            {
                Directory.CreateDirectory(path + folder);
            }
            //上传图片的扩展名
            string fileExtension = fileUpload.FileName.Substring(fileUpload.FileName.LastIndexOf('.'));


            //保存图片的文件名
            string saveName = Guid.NewGuid() + fileExtension;

            //保存图片
            string filePath = path + folder + "/" + saveName;

            fileUpload.SaveAs(filePath);

            return UploadDir.Replace("~/", "/") + folder + "/" + saveName;
        }
    }
}